package com.gzhryc.net_marketing.cloud.micro.api.jetty;

import java.util.EnumSet;

import javax.servlet.DispatcherType;

import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.server.handler.DefaultHandler;
import org.eclipse.jetty.server.handler.HandlerCollection;
import org.eclipse.jetty.server.session.SessionHandler;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.util.thread.QueuedThreadPool;

import com.gzhryc.common.config.PropertyTools;
import com.gzhryc.common.logging.Logger;
import com.gzhryc.net_marketing.cloud.micro.api.MicroConstants;

/**
 * Jetty服务
 * @author zhanghao
 *
 */
public class JettyHttpServer {
	
	final static Logger log = Logger.getLogger(JettyHttpServer.class);

	public static void start() throws Exception {
		QueuedThreadPool threadPool = new QueuedThreadPool();
	    threadPool.setMaxThreads(700);
		Server server = new Server(threadPool);
		
        ServerConnector connector = new ServerConnector(server);
        connector.setPort(PropertyTools.get().getInt(MicroConstants.PROGRAM_TYPE + ".Jetty.port"));
        connector.setIdleTimeout(17000);
        connector.setAcceptQueueSize(300);
        server.setConnectors(new Connector[] { connector });


        ServletContextHandler context = new ServletContextHandler();
        context.setContextPath("/");
        context.addServlet(MainServlet.class, "/*");
        
        context.addFilter(SecurityFilter.class, "/*", EnumSet.of(DispatcherType.REQUEST));

        SessionHandler sh = new SessionHandler();
        context.setSessionHandler(sh);

        HandlerCollection handlers = new HandlerCollection();
        handlers.setHandlers(new Handler[] { context, new DefaultHandler() });
        server.setHandler(handlers);
        
        log.info("**************************************************");
		log.info("*                                                *");
		log.info("*         HTTP服务启动，端口：" + connector.getPort() + "         *"); 
		log.info("*                                                *");
		log.info("**************************************************");
		
        server.start();
        server.join();
	}
	
	
}
